package com.javasm.adminapi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@Slf4j
public class QiniuKodoUtil {

    //七牛云，个人空间，申请的密钥  AK 和  SK
    private static final String accessKey = "t0oUPjPwjqQiS2EM3vm5FIIGI8InWKOOXeNnFpZg";
    private static final String secretKey = "66Hd-TKVVbwRrHSTtiQqE8i8L-VOsUaJ1iWTO8rv";
    //空间名称，申请
    private static final String bucketName = "javasmcd";
    //域名的前缀
    private static final String domain = "http://cd.ray-live.cn/";

    /**
     * 获取七牛token，返回给客户端
     * 不论是服务端上传，还是客户端js上传，都需要服务端生成token值
     * 根据ak 和 sk 算出来的值
     *
     * @return
     */
    public static String getToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucketName);
    }

    /**
     * 返回域名
     * 给js 返回七牛云的域名
     *
     * @return
     */
    public static String getDomain() {
        return domain;
    }

    /**
     * 上传头像图片到七牛云存储
     * @param multipartFile 用户上传的图片文件
     * @return 上传成功后返回的文件访问URL
     */
    //上传头像
    public static String uploadWebHeadPic(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        // 构造七牛云存储的文件key，包含路径和随机文件名
        String key = "68/web_upload/" + RandomUtil.getFileName(fileName);
//        multipartFile.getInputStream();
//        multipartFile.getBytes();
        //file上传到七牛云
        try {
            return baseBytes(multipartFile.getBytes(), key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static String uploadAdminHeadPic(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String key = "68/admin_upload/" + RandomUtil.getFileName(fileName);
        try {
            return baseBytes(file.getBytes(), key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    //上传 在线 图片
    public static String uploadUrl(String url) {
        if (url == null) {
            return null;
        }
        try {
            //模拟浏览器，打开了图片，创建了一个URL对象，获取URL对象的流信息
            InputStream inputStream = new URL(url).openStream();
            //获取文件的后缀
            String fileExtension = getFileExtension(url);
            String fileName = RandomUtil.getFileName(fileExtension);
            if (fileExtension.isEmpty()){
                fileName = null;
            }
            String key = "68/url/"+fileName;
            return baseBytes(inputStream.readAllBytes(),key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFileExtension(String name) {
        int j = name.lastIndexOf("?");
        String url = (j == -1)?name:name.substring(0,j);
        int i = url.lastIndexOf(".");
        return (i == -1) ? "" : url.substring(i);
    }
    public static String uploadAiPic(byte[] imageData) {
        //获取文件的后缀
        String fileName = RandomUtil.getFileName(".png");
        String key = "68/ai/"+fileName;
        return baseBytes(imageData,key);
    }
    public static String baseBytes(byte[] uploadBytes, String key) {
        //区域
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String uploadToken = getToken();
        try {
            Response response = uploadManager.put(uploadBytes, key, uploadToken);
            //DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return domain + key;
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

    //mvc上传文件，接收到的是MultipartFile对象
    public static String upload(MultipartFile multipartFile) {
        //如果文件是空，不处理
        if (multipartFile == null) {
            return null;
        }
        //获取，当前空间的 位置，如果你申请的是其他节点，不是华南的，记得修改这个属性
        Configuration cfg = new Configuration(Region.region2());
        //分片上传
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        //文件名，如果key是null，就会按照哈希值给文件名赋值
        //根据图片内容，生成的哈希值，相同的图片，重复上传，只有1个文件
        String key = multipartFile.getOriginalFilename();
        String upToken = getToken();//获取token参数
        try {
            // 获取inputStream对象  response 是上传之后的结果
            Response response = uploadManager.put(multipartFile.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            log.info(putRet.key);
            log.info(domain + putRet.key);
            return domain + putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String upload(String filePath) {
        return upload(new File(filePath));
    }

    public static String upload(File file) {
        //构造一个带指定 Region 对象的配置类
        /**
         * 华东	Region.region0(), Region.huadong()
         * 华北	Region.region1(), Region.huabei()
         * 华南	Region.region2(), Region.huanan()
         * 北美	Region.regionNa0(), Region.beimei()
         * 东南亚	Region.regionAs0(), Region.xinjiapo()
         */
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        String upToken = getToken();
        try {
            Response response = uploadManager.put(file, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            log.info(putRet.key);
            log.info(domain + putRet.hash);
            return domain + putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String path = "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/7d/31/20250925/6296b724/24425609-553d-47fc-89f3-77a78110c730-1.png?Expires=1759370755&OSSAccessKeyId=LTAI5tKPD3TMqf2Lna1fASuh&Signature=law2lW6EmLnnYjzqIhKixJq0zPc%3D";
        String fileExtension = getFileExtension(path);
        System.out.println(fileExtension);
        /*String s = QiniuKodoUtil.uploadUrl(path);
        System.out.println(s);*/
    }



}
